package com.unsiv.helicopter;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl;
import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener;
import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.extension.input.touch.controller.MultiTouch;
import org.anddev.andengine.extension.input.touch.controller.MultiTouchController;
import org.anddev.andengine.extension.input.touch.exception.MultiTouchException;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.font.FontFactory;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.sensor.accelerometer.AccelerometerData;
import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import org.anddev.andengine.util.Callback;
import org.anddev.andengine.util.MathUtils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.media.AudioManager;
import android.widget.Toast;

import com.unsiv.helicopter.entity.Accelerator;
import com.unsiv.helicopter.entity.Adjustment;
import com.unsiv.helicopter.entity.Button;
import com.unsiv.helicopter.entity.Channel;
import com.unsiv.helicopter.entity.Dashboard;

/**
 * 
 * @author fanzhen
 * @time 3:08:05 PM Oct 28, 2011
 * @email fanzhen.meng@gmail.com
 * @qq 474146502
 * @phone 13953109657
 */
public class MainActivity extends BaseGameActivity implements IAccelerometerListener, Callback<Integer> {
	// 窗口
	private Camera mCamera;
	private static final int CAMERA_WIDTH = 800;
	private static final int CAMERA_HEIGHT = 480;
	// 字体
	private BitmapTextureAtlas mFontTexture;
	private Font mFont;
	// 资源
	private BitmapTextureAtlas mBackgroundTexture;
	private TextureRegion mBackgroundTextureRegion;
	private BitmapTextureAtlas mLogoTexture;
	private TiledTextureRegion mLogoTextureRegion;
	private BitmapTextureAtlas mBackTexture;
	private TiledTextureRegion mBackRegion;
	private BitmapTextureAtlas mSensorTexture;
	private TiledTextureRegion mSensorRegion;
	private BitmapTextureAtlas mReturnTexture;
	private TiledTextureRegion mReturnRegion;
	private BitmapTextureAtlas mLightTexture;
	private TiledTextureRegion mLightRegion;
	private BitmapTextureAtlas mSwitcherTexture;
	private TiledTextureRegion mSwitcherRegion;
	private BitmapTextureAtlas mAcceleratorTexture;
	private TiledTextureRegion mAcceleratorRegion;
	private BitmapTextureAtlas mChannelTexture;
	private TiledTextureRegion mChannelRegion;
	private BitmapTextureAtlas mOnScreenControlTexture;
	private TextureRegion mOnScreenControlBaseTextureRegion;
	private TextureRegion mOnScreenControlKnobTextureRegion;
	private BitmapTextureAtlas mAdjustmentTexture;
	private TiledTextureRegion mLeftRegion;
	private TiledTextureRegion mRightRegion;

	private BitmapTextureAtlas mDashboardTexture;
	private TextureRegion mDashboardRegion;
	private BitmapTextureAtlas mPointerTexture;
	private TextureRegion mPointerRegion;
	// 控件
	private Scene mScene;
	private Accelerator accelerator;
	private Dashboard dashboard;
	private Channel channel;
	private Adjustment adjustment;
	private AnalogOnScreenControl mDigitalOnScreenControl;
	private Button switcher;
	
	boolean flagSensor = false;

	BroadcastReceiver headSetReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
				if (intent.getIntExtra("state", 0) != 0) {
					// headphone plugged
					Command.needDoCommand = true;
				} else {
					// headphone unplugged
					Command.needDoCommand = false;
					Command.allowCommand = false;
					if (switcher != null)
						switcher.setCurrentTileIndex(0);
					Toast.makeText(getApplicationContext(), "Sorry , please insert a headSet!!", Toast.LENGTH_SHORT).show();
				}
			}
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_HEADSET_PLUG);
		registerReceiver(headSetReceiver, filter);
	}

	@Override
	protected void onPause() {
		Command.allowCommand = false;
		unregisterReceiver(headSetReceiver);
		super.onPause();
	}

	@Override
	public Engine onLoadEngine() {
		AudioManager manager = (AudioManager) getSystemService(Activity.AUDIO_SERVICE);
		// 设置最大音量
		int maxv1 = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		int maxv2 = manager.getStreamMaxVolume(AudioManager.STREAM_RING);
		int maxv3 = manager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);
		int maxv4 = manager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
		manager.setStreamVolume(AudioManager.STREAM_RING, maxv2, 0);
		manager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, maxv3, 0);
		manager.setStreamVolume(AudioManager.STREAM_ALARM, maxv4, 0);
		manager.setStreamVolume(AudioManager.STREAM_MUSIC, maxv1, 0);
		manager.setStreamVolume(AudioManager.STREAM_MUSIC, maxv1, AudioManager.FLAG_PLAY_SOUND);
		this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		final Engine engine = new Engine(
				new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera).setNeedsSound(true));
		try {
			if (MultiTouch.isSupported(this)) {
				engine.setTouchController(new MultiTouchController());
			} else {
				Toast.makeText(this,
						"Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.",
						Toast.LENGTH_SHORT).show();
			}
		} catch (final MultiTouchException e) {
			Toast.makeText(this,
					"Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.",
					Toast.LENGTH_SHORT).show();
		}
		return engine;
	}

	@Override
	public void onLoadResources() {
		FontFactory.setAssetBasePath("font/");
		this.mFontTexture = new BitmapTextureAtlas(512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mFont = FontFactory.createFromAsset(this.mFontTexture, this, "Plok.ttf", 32, true, Color.WHITE);
		this.mEngine.getTextureManager().loadTexture(this.mFontTexture);
		this.getFontManager().loadFont(this.mFont);
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
		// 背景+Logo
		this.mBackgroundTexture = new BitmapTextureAtlas(1024, 1024, TextureOptions.DEFAULT);
		this.mBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBackgroundTexture, this, "background.png", 0, 0);
		this.mLogoTexture = new BitmapTextureAtlas(256, 64, TextureOptions.DEFAULT);
		this.mLogoTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mLogoTexture, this, "logo.png", 0, 0, 1, 1);
		this.mEngine.getTextureManager().loadTextures(this.mBackgroundTexture, this.mLogoTexture);
		// buttons
		this.mBackTexture = new BitmapTextureAtlas(256, 128, TextureOptions.DEFAULT);
		this.mBackRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBackTexture, this, "back.png", 0, 0, 2, 1);
		this.mSensorTexture = new BitmapTextureAtlas(256, 128, TextureOptions.DEFAULT);
		this.mSensorRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mSensorTexture, this, "sensor.png", 0, 0, 2, 1);
		this.mReturnTexture = new BitmapTextureAtlas(256, 128, TextureOptions.DEFAULT);
		this.mReturnRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mReturnTexture, this, "return.png", 0, 0, 2, 1);
		this.mLightTexture = new BitmapTextureAtlas(256, 128, TextureOptions.DEFAULT);
		this.mLightRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mLightTexture, this, "light.png", 0, 0, 2, 1);

		// 通道+油门+仪表盘
		this.mAcceleratorTexture = new BitmapTextureAtlas(1024, 1024, TextureOptions.DEFAULT);
		this.mAcceleratorRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mAcceleratorTexture, this, "acctor.png", 0, 0, 5, 2);
		this.mChannelTexture = new BitmapTextureAtlas(1024, 1024, TextureOptions.DEFAULT);
		this.mChannelRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mChannelTexture, this, "channel.png", 0, 0, 1, 4);
		this.mEngine.getTextureManager().loadTextures(this.mAcceleratorTexture, this.mChannelTexture);
		this.mSwitcherTexture = new BitmapTextureAtlas(256, 256, TextureOptions.DEFAULT);
		this.mSwitcherRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mSwitcherTexture, this, "switcher.png", 0, 0, 2, 1);
		this.mEngine.getTextureManager().loadTextures(this.mBackTexture, this.mSensorTexture, this.mReturnTexture, this.mLightTexture, this.mSwitcherTexture);
		this.mDashboardTexture = new BitmapTextureAtlas(256, 256, TextureOptions.DEFAULT);
		this.mDashboardRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mDashboardTexture, this, "dashboard.png", 0, 0);
		this.mEngine.getTextureManager().loadTextures(this.mDashboardTexture);
		this.mPointerTexture = new BitmapTextureAtlas(256, 256, TextureOptions.DEFAULT);
		this.mPointerRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mPointerTexture, this, "pointer.png", 0, 0);
		this.mEngine.getTextureManager().loadTextures(this.mPointerTexture);
		// 导航
		this.mOnScreenControlTexture = new BitmapTextureAtlas(1024, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "control.png", 0, 0);
		this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "control_airplane.png", 512,
				0);
		this.mEngine.getTextureManager().loadTextures(this.mOnScreenControlTexture);
		// 微调
		this.mAdjustmentTexture = new BitmapTextureAtlas(128, 256, TextureOptions.DEFAULT);
		this.mLeftRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mAdjustmentTexture, this, "left.png", 0, 0, 1, 2);
		this.mRightRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mAdjustmentTexture, this, "right.png", 0, 124, 1, 2);
		this.mEngine.getTextureManager().loadTextures(this.mAdjustmentTexture);
	}

	@Override
	public Scene onLoadScene() {
		// this.mEngine.registerUpdateHandler(new FPSLogger());
		this.mScene = new Scene();
		this.mScene.setOnAreaTouchTraversalFrontToBack();
		this.mScene.setBackgroundEnabled(false);
		this.mScene.attachChild(new Sprite(0, 0, this.mBackgroundTextureRegion));
		// this.mScene.attachChild(new Sprite(CAMERA_WIDTH -
		// mLogoTextureRegion.getWidth(), CAMERA_HEIGHT -
		// mLogoTextureRegion.getHeight(), this.mLogoTextureRegion));
		Button logo = new Button(getApplicationContext(),CAMERA_WIDTH - mLogoTextureRegion.getWidth(), CAMERA_HEIGHT - mLogoTextureRegion.getHeight(), this.mLogoTextureRegion, Button.LOGO);
		logo.setCallback(this);// 注册回调
		this.mScene.attachChild(logo);
		this.mScene.registerTouchArea(logo);
		Button back = new Button(getApplicationContext(),0, 0, this.mBackRegion, Button.BACK);
		back.setCallback(this);// 注册回调
		this.mScene.attachChild(back);
		this.mScene.registerTouchArea(back);
		Button sensor = new Button(getApplicationContext(),CAMERA_WIDTH - this.mSensorRegion.getWidth() / 2, 0, this.mSensorRegion, Button.SENSOR);
		sensor.setCallback(this);// 注册回调
		this.mScene.attachChild(sensor);
		this.mScene.registerTouchArea(sensor);
		Button retu = new Button(getApplicationContext(),300, 110, this.mReturnRegion, Button.RETURN);
		retu.setCallback(this);// 注册回调
		this.mScene.attachChild(retu);
		this.mScene.registerTouchArea(retu);
		Button light = new Button(getApplicationContext(),300, 210, this.mLightRegion, Button.LIGHT);
		this.mScene.attachChild(light);
		this.mScene.registerTouchArea(light);
		switcher = new Button(getApplicationContext(),300, 310, this.mSwitcherRegion, Button.SWITCHER);
		this.mScene.attachChild(switcher);
		this.mScene.registerTouchArea(switcher);
		adjustment = new Adjustment(getApplicationContext(),250, CAMERA_HEIGHT - this.mLeftRegion.getHeight() + 50, this.mLeftRegion, mRightRegion, mFont);
		this.mScene.attachChild(adjustment);
		this.mScene.registerTouchArea(adjustment.left);
		this.mScene.registerTouchArea(adjustment.right);
		accelerator = new Accelerator(getApplicationContext(),50, 140, Accelerator.WIDTH, Accelerator.HEIGHT, mAcceleratorRegion);
		this.mScene.attachChild(accelerator);
		this.mScene.registerTouchArea(accelerator);
		this.dashboard = new Dashboard(20, 50, 213, 169, mDashboardRegion,mPointerRegion, accelerator);
		this.mScene.attachChild(dashboard);
		channel = new Channel(CAMERA_WIDTH / 4, 0, this.mChannelRegion);
		this.mScene.attachChild(channel);
		this.mScene.registerTouchArea(channel);
		final int x1 = CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion.getWidth();
		final int y1 = (CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight()) / 3 * 2;
		this.mDigitalOnScreenControl = new AnalogOnScreenControl(x1, y1, mCamera, mOnScreenControlBaseTextureRegion, mOnScreenControlKnobTextureRegion, 0.1f,
				new IAnalogOnScreenControlListener() {
					@Override
					public void onControlChange(BaseOnScreenControl pBaseOnScreenControl, float pValueX, float pValueY) {
						if (pValueX == 0 && pValueY == 0) {
							Command.mLeftOrRight = 0;
							Command.mValueOfLR = 0;
							Command.mForwardOrBack = 0;
							Command.mValueOfFB = 0;
							return;
						}
						final float angle = MathUtils.radToDeg(MathUtils.atan2(pValueX, pValueY)) + 180;
						if (angle > 45 && angle <= 135) {
							Command.mLeftOrRight = 1;
							Command.mValueOfLR = (int) (63 * MathUtils.distance(pValueX, pValueY, 0, 0));
						} else if (angle > 135 && angle <= 225) {
							Command.mForwardOrBack = 2;
							Command.mValueOfFB = (int) (63 * MathUtils.distance(pValueX, pValueY, 0, 0));
						} else if (angle > 225 && angle <= 315) {
							Command.mLeftOrRight = 2;
							Command.mValueOfLR = (int) (63 * MathUtils.distance(pValueX, pValueY, 0, 0));
						} else if (angle > 315 || angle <= 45) {
							Command.mForwardOrBack = 1;
							Command.mValueOfFB = (int) (63 * MathUtils.distance(pValueX, pValueY, 0, 0));
						}
					}
					@Override
					public void onControlClick(AnalogOnScreenControl pAnalogOnScreenControl) {
					}
				});
		this.mDigitalOnScreenControl.setOnControlClickEnabled(false);

//		this.mDigitalOnScreenControl.setOnAreaTouchListener(new IOnAreaTouchListener() {
//			@Override
//			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
//					ITouchArea pTouchArea, float pTouchAreaLocalX,
//					float pTouchAreaLocalY) {
//				if(!Command.needDoCommand){
//					Toast.makeText(getApplicationContext(), "Sorry please insert a handset.",
//							Toast.LENGTH_SHORT).show();
//					return false;
//				}
//				if(!Command.allowCommand){
//					Toast.makeText(getApplicationContext(),
//							"Sorry please turn on the swither.",
//							Toast.LENGTH_SHORT).show();
//					return false;
//				}
//				return true;
//			}
//		});
		this.mDigitalOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		this.mDigitalOnScreenControl.refreshControlKnobPosition();
		this.mDigitalOnScreenControl.getControlKnob().setAlpha(0f);
		this.mScene.setChildScene(mDigitalOnScreenControl);
		this.mScene.setTouchAreaBindingEnabled(true);
		this.enableAccelerometerSensor(this);
		return mScene;
	}

	@Override
	public void onLoadComplete() {
		if(Command.needDoCommand){
			Toast.makeText(getApplicationContext(), "please turn on the swither!!", Toast.LENGTH_SHORT).show();
		}
		// MyAudioHelper.playCommand();
		// this.mScene.registerUpdateHandler(new TimerHandler(0.02f, true, new
		// ITimerCallback() {
		// @Override
		// public void onTimePassed(final TimerHandler pTimerHandler) {
		// MainActivity.this.mScene.unregisterUpdateHandler(pTimerHandler);
		// if(Command.allowCommand)MyAudioHelper.play1();
		// }
		// }));
		// this.mScene.registerUpdateHandler(new TimerHandler(0f, true, new
		// ITimerCallback() {
		// @Override
		// public void onTimePassed(final TimerHandler pTimerHandler) {
		// if(Command.allowCommand)MyAudioHelper.play2();
		// }
		// }));
	}
	@Override
	public void onAccelerometerChanged(AccelerometerData pAccelerometerData) {
		if(flagSensor){
			this.mDigitalOnScreenControl.onUpdateControlKnob(pAccelerometerData.getX() / 10 / 2, pAccelerometerData.getY() / 10 / 2);
		}else{
			if(Button.isAllowSensor){
				if(pAccelerometerData.getY()<-9){
					this.mDigitalOnScreenControl.setRotation(180f);
					this.mCamera.setRotation(180f);
				}
				if(pAccelerometerData.getY()>9){
					this.mCamera.setRotation(0f);
					this.mDigitalOnScreenControl.setRotation(0f);
				}
			}
		}
	}
	@Override
	public void onCallback(Integer pCallbackValue) {
		if (pCallbackValue == 0) {
			this.mDigitalOnScreenControl.onUpdateControlKnob(0, 0);
			this.mDigitalOnScreenControl.registerTouchArea(mDigitalOnScreenControl.getControlBase());
			flagSensor = false;
			Button.isAllowSensor = true;
		} else if (pCallbackValue == 1) {
			Button.isAllowSensor = false;
			flagSensor = true;
			this.mDigitalOnScreenControl.unregisterTouchArea(mDigitalOnScreenControl.getControlBase());
		} else if (pCallbackValue == 2) {
			this.onBackPressed();
		} else if (pCallbackValue == 6) {
			startActivity(new Intent(getApplicationContext(), CompanyActivity.class));
		}
	}
}